﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics ;

namespace VBGBuilder {
  class SVNFactory {

    String _svnCommand;
    Process _proc;
    Dictionary<String, Boolean> _updated = new Dictionary<String , Boolean>(10);

    public SVNFactory(FileInfo svnExe) {
      _svnCommand = svnExe.ToString();
      process.StartInfo.FileName = _svnCommand;
    }

    public void update(VBFile vbFile, Boolean waitOnIt) {
      DirectoryInfo  dir = vbFile.file.Directory ;
      String url = dir.FullName ;
      try {
        if (_updated[url]) {
          return;
        }
      }
      catch (Exception e){
      }

      checkOutDirectory(dir, vbFile.dlg, waitOnIt, true);

    }

    private void checkOutDirectory(DirectoryInfo directory, DLG dlg, Boolean waitOnIt, Boolean recursive) {
      DirectoryInfo currDir = directory;
      DirectoryInfo root = dlg.root;
   
      String arguments = "";
      while (currDir.FullName != root.FullName ) {
        checkOutDirectory(directory.Parent, dlg, waitOnIt, false );

        if (!currDir.Exists) {
          arguments = "co ";
        }
        else {
          arguments = "up ";
        }

        if (!recursive) {
          arguments += "-N ";
        }

        String url = currDir.FullName;
        try {
          if (_updated[url]) {
            return;
          }
        }
        catch (Exception e) {
        }
        _updated.Add(url, true);

        url = url.Replace(root.FullName, "");
        url = dlg.svnURL + url.Replace("\\", "/");
        arguments += "\"" + url + "\" \"" + currDir.FullName + "\"";

        process.StartInfo.Arguments = arguments;
        process.Start();
        if (waitOnIt) {
          process.WaitForExit(10000);
        }
      }
    }

    private Process process {
      get {
        if (_proc == null) {
          _proc = new Process();
          _proc.EnableRaisingEvents = false;
          _proc.StartInfo.UseShellExecute = false;
        }
        return _proc; 
      }
    }

  }
}
